﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.IO;
using System.Text;
namespace LogAnalysis {
	public class Utility {
		//private static string connstring = "Data Source=|DataDirectory|TempData.sdf;";
		private static string connstring = "Data Source=.;Initial Catalog=test;Integrated Security=True";
		public static DataTable ReadFileToTable(string filePath, string encode) {
			string[] stringContent = File.ReadAllLines(filePath, Encoding.GetEncoding(encode));

			string[] fields = new string[] { };
			DataTable tmpData = new DataTable();
			for (var c = 0; c < stringContent.LongLength; c++) {
				var tmpstring = stringContent[c];
				if (tmpstring.StartsWith("#")) {
					if (tmpstring.StartsWith("#Fields:") && tmpData.Columns.Count == 0) {
						fields = tmpstring.Replace("#Fields:", "").Trim().Split(' ');
						for (var c2 = 0; c2 < fields.Length; c2++) {
							tmpData.Columns.Add(fields[c2]);
						}
					}
				}
				else {
					var tmpArray = stringContent[c].Split(' ');
					if (fields.Length == tmpArray.Length) {
						tmpData.Rows.Add(tmpArray);
					}
				}
			}
			return tmpData;
		}

		public static string CreateTableScript(DataTable table) {
			StringBuilder script = new StringBuilder();
			script.Append("CREATE TABLE [IISLOG](");
			for (int i = 0; i < table.Columns.Count; i++) {
				script.AppendFormat("[{0}] [nvarchar]({1}) NULL", table.Columns[i].ColumnName, table.Columns[i].MaxLength);
			}
			script.Append(")");
			return script.ToString();
		}

		public static void ExecuteScript(string script, params KeyValuePair<string, object>[] p) {
			//ExecuteScriptCe(script, p);
			//return;
			SqlConnection conn = null;

			try {
				conn = new SqlConnection(connstring);
				conn.Open();
				SqlCommand cmd = conn.CreateCommand();
				cmd.CommandText = script;
				foreach (var item in p) {
					cmd.Parameters.AddWithValue(item.Key, item.Value);
				}
				cmd.ExecuteNonQuery();
			}
			finally {
				conn.Close();
			}

		}

		public static void ExecuteScriptCe(string script, params KeyValuePair<string, object>[] p) {
			SqlCeConnection conn = null;

			try {
				conn = new SqlCeConnection(connstring);
				conn.Open();
				SqlCeCommand cmd = conn.CreateCommand();
				cmd.CommandText = script;
				foreach (var item in p) {
					cmd.Parameters.AddWithValue(item.Key, item.Value);
				}
				cmd.ExecuteNonQuery();
			}
			finally {
				conn.Close();
			}

		}
	}
}
